package com.imooc.mq;



import com.imooc.enums.ArticleStatus;
import com.imooc.service.ArticleService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author liansen
 * @create 06-18-15:41
 */
@Slf4j
@Component
public class RabbitMQDelayConsumer_Article {

    @Autowired
    private ArticleService articleService;

    @RabbitListener(queues = {DelayConfig_Article.QUEUE_DELAY_ARTICLE})
    public void watchQueue(String content, Message msg, Channel channel) throws IOException {

        try{
            //获取接收到的路由键
            String receivedRoutingKey = msg.getMessageProperties().getReceivedRoutingKey();

            //判断接收到的路由键和自己设置的路由键是否一致
            if(receivedRoutingKey.equalsIgnoreCase(DelayConfig_Article.DELAY_BINDING_ARTICLE)){

                log.info("10秒后监听到延迟队列");
                log.info("接收到的消息:" + content);
                //接收到的content就是发过来的文章主键
                //接收到之后将这个文章状态改为正常可见
                articleService.updateStatus(content, ArticleStatus.OPEN.type);
            }
            //deliveryTag: 消息投递的标签  boolean multiple: 批量确认所有消费者获得的消息
            channel.basicAck(msg.getMessageProperties().getDeliveryTag(), true);
        }catch (Exception e){
            //long deliveryTag: 消息投递的标签  boolean multiple: 批量确认所有消费者获得的消息, requeue: 是否重回队列
            channel.basicNack(msg.getMessageProperties().getDeliveryTag(), true, true);
        }


    }
}
